<template>
  <div>
    <!--增加或更新的表单弹窗-->
    <div style="text-align: left; margin: 10px">
      <el-button size="mini" type="primary" @click="toAdd">
        添加
      </el-button>

      <!--查询-->
      <el-input type="text"
                style="width: 200px; margin: 0px 5px;"
                placeholder="学号"
                size="mini"
                v-model="searchParams.studentNo" clearable>
      </el-input>
      <el-input type="text"
                style="width: 200px; margin: 0px 5px;"
                placeholder="姓名"
                size="mini"
                v-model="searchParams.name" clearable>
      </el-input>
      <el-button size="mini" @click="clearSearchParams">
        清空
      </el-button>
      <el-button size="mini" type="primary" @click="search">
        查询
      </el-button>
    </div>

    <!--表单-->
    <el-dialog :title=formTitle :visible.sync="formDialogVisible">
      <el-form ref="form" :model="formData" :rules="rules" size="large" label-width="100px">
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="formData.studentNo" :maxlength="9"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="handelConfirm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--列表-->
    <div style="margin: 0px 10px;text-align: left;">
      <el-table
        :data="students"
        stripe
        :default-sort="{prop: 'studentNo', order: 'asc'}">

        <el-table-column prop="studentNo" label="学号" sortable></el-table-column>
        <el-table-column prop="name" label="姓名" sortable></el-table-column>
        <el-table-column prop="addressDetail" label="寝室" sortable></el-table-column>
        <el-table-column label="冻结状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="green"
              inactive-color="red"
              @change="(value) => commitStatusChange(value, scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <el-button @click="resetStudent(scope.row.id)" type="text" size="mini">重置</el-button>
            <el-button @click="toEdit(scope.row)" type="text" size="mini">编辑</el-button>
            <el-button type="text" size="mini" @click="toDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-row style="float: right">
        <el-pagination
          @current-change="changePageNo"
          @size-change="changePageSize"
          :current-page.sync="searchParams.pageNo"
          :page-sizes="[5, 10, 20, 30, 50, 100]"
          :page-size.sync="searchParams.pageSize"
          layout=" total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-row>

    </div>
  </div>
</template>

<script>
  import {addStudent, deleteStudents, searchStudents, updateStudent,resetStudentInfo} from "@/api/modules/app/studentApi.js";

  export default {
    name: "studentComponent",
    data() {
      return {
        students: [],
        searchParams: {
          studentNo: null,
          name: null,
          currentPage: 1,
          pageSize: 10
        },
        total: 0,
        formDialogVisible: false,
        formTitle: '添加',
        formData: {
          id: null, studentNo: null, name: null
        },
        rules: {
          studentNo: [
            {required: true, pattern: /^\d{9}$/, message: "学号格式不正确", trigger: "blur"}
          ], name: [
            {required: true, message: '姓名不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    created() {
      this.search()
    },
    methods: {
      // 清除查询参数
      clearSearchParams() {
        this.searchParams = {
          studentNo: null,
          name: null
        }
        this.currentPage = 1;
        this.search();
      },
      // 切换页数
      changePageNo(pageNo) {
        this.searchParams.pageNo = pageNo;
        this.search()
      },
      // 改变页面大小
      changePageSize(pageSize) {
        this.searchParams.pageSize = pageSize;
        this.search()
      },
      // 查询
      search() {
        searchStudents(this.searchParams.studentNo, this.searchParams.name, this.currentPage, this.pageSize)
          .then(result => {
            this.students = result.data.records;
            this.total = result.data.total;
          })
      },
      // 重置表单
      resetForm() {
        // 手动重置 不然数据被绑定在toEdit时深克隆出来的对象
        this.formData = {
          id: null, studentNo: null, openid: null, password: null, addressId: null, name: null, status: null
        }
      },
      // 增加
      toAdd() {
        this.resetForm()
        this.formDialogVisible = true
        this.formTitle = '增加'
      },
      // 删除
      toDelete(id) {
        let that = this;
        this.$confirm("提示", "是否删除", {}).then(() => {
          deleteStudents([id]).then(() => {
            this.$notify.success({
              title: '删除成功',
              duration: 500
            })
            that.search();
          })
        }).catch(() => {
        })
      },
      // 编辑
      toEdit(selectedStudent) {
        // 深拷贝一个对象 不然在表格显示的数据会受到印象
        this.formData = JSON.parse(JSON.stringify(selectedStudent));
        this.formData.studentNo = "" + selectedStudent.studentNo; // 强转为string
        this.formDialogVisible = true
        this.formTitle = '更新'
      },
      // 提交表单
      handelConfirm() {
        this.$refs['form'].validate(valid => {
          console.log(this.formTitle)
          if (!valid)
            return

          this.formDialogVisible = false;
          if (this.formTitle.startsWith('增加')) {
            addStudent(this.formData).then(result => {
              if (result.code !== 200)
                return;
              this.$notify({
                title: "增加成功",
                type: "success",
                duration: 1000
              });
              this.search()
            })
          } else if (this.formTitle.startsWith('更新')) {
            updateStudent(this.formData).then(result => {
              this.$notify({
                title: "更新成功",
                type: "success",
                duration: 1000
              });
              this.search()
            })
          }
        })
      },
      // 重置学生数据
      resetStudent(id) {
        this.$confirm("重置学员数据?", {
          type: 'danger'
        }).then(() => {
          resetStudentInfo(id).then(() => {
            this.$notify.success("重置成功");
            this.search();
          })
        }).catch(() => {
        })
      },
      // 冻结账号
      commitStatusChange(value, student) {
        this.$confirm(value === false ? '冻结账号?' : '激活账号').then(() => {
          let temp = {
            id: student.id,
            status: student.status
          }
          updateStudent(temp).then(() => {
            this.$notify.success(value === false ? "已冻结" : "已激活")
          }).catch(() => {
            student.status = !student.status;
          })
        }).catch(() => {
          student.status = !student.status;
        })
      },
    }
  }
</script>

